import getOpenID from "../getOpenID"

const FEED_INTERVAL = 60*1000

export const getFeedInfo = async (userAdoptId) =>{
  const infoCache = wx.getStorageSync('feedInfo') || {}

  if(infoCache[userAdoptId]){
    return infoCache[userAdoptId]
  }

  const {openid} = await getOpenID()

  const {result:[result]} = await wx.cloud.callFunction({
    name: "farm",
    data:{
      $url:'getFeedInfo',
      openid,
      userAdoptId
    }
  })

  const info = wx.getStorageSync('feedInfo') || {}
  info[userAdoptId] = result
  wx.setStorageSync('feedInfo', info)
  
  return result 
}

export const setFeedInfo = async (userAdoptId) =>{
  const {openid} = await getOpenID()
  const feedTime = Date.now()
  const nextTime = Date.now() + FEED_INTERVAL
  const res = await wx.cloud.callFunction({
    name: "farm",
    data:{
      $url:'setFeedInfo',
      openid,
      userAdoptId,
      feedTime,
      nextTime
    }
  })

  const info = wx.getStorageSync('feedInfo')|| {}
  info[userAdoptId] = {
    openid, userAdoptId, feedTime, nextTime
  }

  wx.setStorageSync('feedInfo', info)
}

export const canFeed = async (userAdoptId) =>{
  const feedInfo = await getFeedInfo(userAdoptId)
  // console.log(feedInfo);
  if(feedInfo){
    // 返回的数组中 有两个值 ， 一个是布尔值 当前小鸡或者土豆能不能喂
    return [Date.now() >= feedInfo.nextTime,feedInfo.nextTime]
  }else{
    return [true,-1]
  }
}
